package com.zygh.interactiveplatform.task;


import cn.hutool.core.date.SystemClock;
import com.zygh.interactiveplatform.module.entity.vo.NetVO;
import lombok.extern.slf4j.Slf4j;
import org.hyperic.sigar.NetInterfaceConfig;
import org.hyperic.sigar.NetInterfaceStat;
import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.SigarException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Objects;

/**
 *  网络net流量定时任务
 *
 */
@Slf4j
@Configuration
@EnableScheduling
public class NetScheduleTask {

    @Resource
    private RedisTemplate redisTemplate;
//    @Value("${monitor.switch}")
//    private Boolean monitorSwitch;

    @Scheduled(cron = "40 03 14 * * ?")
    private void task() {
        if(isLocal()){
            // 此处简短实现不执行。 实际上定时任务还在执行
            log.info("window环境，停止定时任务……");
            return;
        }
        if(true){
            long start = SystemClock.now();
            log.info("网络net流量定时任务start……");
            run();
            log.info("网络net流量定时任务end，耗时：{}ms……", (SystemClock.now()-start));
        }
    }

    /**
     *  执行
     */
    private void run(){
        Date now = new Date();
        // 获取当前时间下的网络状态
        NetVO net = null;
        try{
            net = net();
        }catch (Exception e){
            log.error("定时任务异常：{}", e.getMessage());
            return;
        }
        net.setCurrentTime(now);
        // 取出redis数据
        Long size = redisTemplate.opsForList().size("redis的key");
        if(Objects.isNull(size) || 0 == size){
            // 说明list为空
            net.setCurrentRxPackets(0L);
            net.setCurrentTxPackets(0L);
            net.setCurrentRxBytes(0L);
            net.setCurrentTxBytes(0L);
            redisTemplate.opsForList().leftPush("redis的key", net);
            return;
        }
        // 小于限制的长度时，取出最后一个：计算本次取数
        Object index = redisTemplate.opsForList().index("redis的key", 0L);
        NetVO netVO = (NetVO)index;
        net.setCurrentRxPackets(net.getRxPackets() - netVO.getRxPackets());
        net.setCurrentTxPackets(net.getTxPackets() - netVO.getTxPackets());
        net.setCurrentRxBytes(net.getRxBytes() - netVO.getRxBytes());
        net.setCurrentTxBytes(net.getTxBytes() - netVO.getTxBytes());
        redisTemplate.opsForList().leftPush("redis的key", net);
        // 长度限制
        if(3000 <= size){
            redisTemplate.opsForList().trim("redis的key", 0L, (3000 -1));
        }
    }

    /**
     * 主机网络信息
     */
    private NetVO net() throws SigarException {
        NetVO netVO = new NetVO();
        long rxPackets = 0L, txPackets = 0L, rxBytes = 0L, txBytes = 0L;
        Sigar sigar = new Sigar();
        String ifNames[] = sigar.getNetInterfaceList();
        for (int i = 0; i < ifNames.length; i++) {
            String name = ifNames[i];
            NetInterfaceConfig ifconfig = sigar.getNetInterfaceConfig(name);
            if ((ifconfig.getFlags() & 1L) <= 0L) {
                continue;
            }
            NetInterfaceStat ifstat = sigar.getNetInterfaceStat(name);
            // 接收的总包裹数
            rxPackets += ifstat.getRxPackets();
            // 发送的总包裹数
            txPackets += ifstat.getTxPackets();
            //接收到的总字节数
            rxBytes += ifstat.getRxBytes();
            //发送的总字节数
            txBytes += ifstat.getTxBytes();
        }
        netVO.setRxPackets(rxPackets);
        netVO.setTxPackets(txPackets);
        netVO.setRxBytes(rxBytes);
        netVO.setTxBytes(txBytes);
        return netVO;
    }

    /**
     *  是否window运行，true代表window
     */
    public static boolean isLocal(){
        return System.getProperties().getProperty("os.name").toUpperCase().contains("WINDOWS");
    }
}
